package com.pobos.model

import com.google.appengine.api.datastore.DatastoreServiceFactory
import com.google.appengine.api.datastore.Entity
import com.google.appengine.api.datastore.KeyFactory

abstract class Model {
	
	Entity entity

	static def datastore = DatastoreServiceFactory.datastoreService
	
	public Model(){
		super()
	}
	
	public Model(Map params){
		this.@entity = new Entity(this.getClass().simpleName)
		params.each{ key, val ->
			this.setProperty key, val
		}
	}
	
	public Model(Entity entity){
		this.@entity = entity
	} 
	
	def getProperty(String name) {
		if(name.equals("id")){
			return this.entity.key.id
		} else {
			return this.entity."${name}"
		}
	}
	
	void setProperty(String name, value) {
		entity."${name}" = value
	}
	
	def save(){
		this.entity.save()
	}	
	
	
	def getEntity(entityType, id) {
		def key = KeyFactory.createKey(entityType, id)			
		return this.@datastore.get(key)
	} 
}